//根据后端拿到的数据来生成菜单
import { getRequest } from "./api"

export const initMenu = (router, store)=>{//初始化菜单
  if(store.state.routers.length > 0)return  //routers有数据就直接跳出函数, 不需要初始化

  getRequest('/system/config/menu').then(data=>{   //get请求获取数据,存储数据
    if(data){
      //格式化的router
      let fmtRoutes = formatRoutes(data)
      //添加到router
      router.addRoutes(fmtRoutes)
      //数据放入vuex
      store.commit('initRoutes', fmtRoutes)
    }
  })
}

export const formatRoutes = routes => {//对从服务器拿到的路由信息进行处理
  let fmtRoutes = []
  routes.forEach(router => {
    let {
      path,
      component,
      name,
      iconCls,
      children,
    } = router//对象结构
    if(children && children instanceof Array){
      children = formatRoutes(children) //递归,继续从下层拿数据
    }

    let fmtRouter = {
      path,
      name,
      iconCls,
      children,
      component(resolve){
        if(component.startsWith('Home'))//从home跳转进views路径
        require(['../views/' + component + '.vue'], resolve)
        else if(component.startsWith('Emp'))//根据后端返回的组件名字,拼接对应组件的地址
        require(['../views/emp/' + component + '.vue'], resolve)
        else if(component.startsWith('Per'))
        require(['../views/Per/' + component + '.vue'], resolve)
        else if(component.startsWith('Sal'))
        require(['../views/sal/' + component + '.vue'], resolve)
        else if(component.startsWith('Sta'))
        require(['../views/Sta/' + component + '.vue'], resolve)
        else if(component.startsWith('Sys'))
        require(['../views/sys/' + component + '.vue'], resolve)
      }
    }
    fmtRoutes.push(fmtRouter)
  })
  return fmtRoutes
}